$(() => {
  let $width  = $('#width'),
      $height = $('#height'),
      $btnCal = $('#calc'),
      $perimeter = $('#perimeter'),
      $area   = $('#area'),
      $widthValidate = $('#width-validate'),
      $heightValidate = $('#height-validate');
  //字段级校验
  $width.focusout(() => {
    let result = validate($width,$widthValidate);
    if(!result) {
      $width.select();                      
    }
  });

  $height.focusout(() => {
    let result = validate($height,$heightValidate);
    if(!result) {
      $height.select();
    }          
  });
  //字符级校验
  $width.keypress((e) => {
    let key = e.key,
        val = e.target.value,
        pos = e.target.selectionStart;
    val = val.slice(0,pos) + key + val.slice(pos,val.length);
    if(!/^(0|[1-9]\d*)(\.\d+)?((e|E)(\+|-)?\d+)?$/.test(val)){
      e.preventDefault();
    }
  });
  $height.keypress(function(e) {
    let key = e.key,
        val = e.target.value,
        pos = e.target.selectionStart;
    val = val.slice(0,pos) + key + val.slice(pos,val.length);
    if(!/^(0|[1-9]\d*)(\.\d+)?((e|E)(\+|-)?\d+)?$/.test(val)){
        e.preventDefault();
    }
  });

  //表单级校验
  $btnCal.click(()=> {
    //获取value值
    let w = Number($width.val()),
        h = Number($height.val());

    if(validate($width,$widthValidate) && validate($height,$heightValidate)){
      let p = (w + h) * 2;
      let a = w * h;
      //解决浮点数的舍取误差
      let perimeter = Math.round(p*Math.pow(10,2))/Math.pow(10,2),
          area = Math.round(a*Math.pow(10,2))/Math.pow(10,2);
      //输出
      $perimeter.val(perimeter);
      $area.val(area);
    }
  });
});

function validate(input, output){
  //输入为空
  if(input.val() === ''){
    output.html('该字段不能为空');
    return false;
  } else {
    output.html('');
  }

  //输入为数字
  let val = Number(input.val());
  if(isNaN(val)){
    output.html('该字段应为数字');
    return false;
  } else {
    output.html('');
  }

  //输入为正值
  if(val > 0){
    output.html('');
  } else {
    output.html('该数值应为正');
    return false;
  }

  return true;
}